package com.example.jwtdemo.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.jwtdemo.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HMQ
 * @date 2020/9/20 15:13
 */
public class JWTInterceptor implements HandlerInterceptor {

    /**
     * 拦截注册的前端请求接口
     *
     * @param request  请求
     * @param response 响应
     * @param handle   处理器
     * @return 是否拦截
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
        Map<String, Object> map = new HashMap<>(2);
        //获取请求头部中的令牌（前提是前端得将token放入请求头部）
        String token = request.getHeader("token");
        try {
            //验证token
            JwtUtil.vertify(token);
            //放行请求
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg", "无效签名!");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("msg", "token已过期!");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "token无效！");
        }
        //设置状态
        map.put("state", false);
        //将map转为json返回前端作为响应
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
